package com.yycx.common.jsonp;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

public class GITHUBLoginApater {

    public static String LOGIN_URL = "http://flow.jztit.com/user/login.html";
    public static String USER_AGENT = "User-Agent";
    public static String USER_AGENT_VALUE = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36";

    public static void main(String[] args) throws Exception {

        simulateLogin("cgb311", "888888"); // 模拟登陆github的用户名和密码

    }

    /**
     * @param userName 用户名
     * @param pwd      密码
     * @throws Exception
     */
    public static void simulateLogin(String userName, String pwd) throws Exception {

        /*
         * 第一次请求
         * grab login form page first
         * 获取登陆提交的表单信息，及修改其提交data数据（login，password）
         */
        // get the response, which we will post to the action URL(rs.cookies())
        Connection con = Jsoup.connect(LOGIN_URL);  // 获取connection
        con.header(USER_AGENT, USER_AGENT_VALUE);   // 配置模拟浏览器
        Response rs = con.execute();                // 获取响应
        Document d1 = Jsoup.parse(rs.body());       // 通过Jsoup将返回信息转换为Dom树
        List<Element> eleList = d1.select("form");  // 获取提交form表单，可以通过查看页面源码代码得知

        // 获取cooking和表单属性
        // lets make data map containing all the parameters and its values found in the form
        Map<String, String> datas = new HashMap<>();
//        for (Element e : eleList.get(0).getAllElements()) {
//            // 设置用户名
//            if (e.attr("name").equals("loginName")) {
//                e.attr("value", userName);
//            }
//            // 设置用户密码
//            if (e.attr("name").equals("loginPwd")) {
//                e.attr("value", pwd);
//            }
//            // 排除空值表单属性
//            if (e.attr("name").length() > 0) {
//                datas.put(e.attr("name"), e.attr("value"));
//            }
//        }

        datas.put("loginName","cgb311");
        datas.put("loginPwd","888888");
        datas.put("rememberMe","false");
        datas.put("type","user");

        /*
         * 第二次请求，以post方式提交表单数据以及cookie信息
         */
        Connection con2 = Jsoup.connect("http://flow.jztit.com/user/login");
        con2.header(USER_AGENT, USER_AGENT_VALUE);
        // 设置cookie和post上面的map数据
        Response login = con2.ignoreContentType(true).method(Method.POST)
                .data(datas).execute();
        // 打印，登陆成功后的信息
        System.out.println(login.body());

        // 登陆成功后的cookie信息，可以保存到本地，以后登陆时，只需一次登陆即可
        Map<String, String> map = login.cookies();
        for (String s : map.keySet()) {
            System.out.println(s + " : " + map.get(s));
        }
        httpPost(map,"http://flow.jztit.com/_yvanui/query");
    }

    private static String httpPost(Map<String, String> sessionId, String url) throws IOException {
        //获取请求连接
        Connection con = Jsoup.connect(url);
        con.header(USER_AGENT, USER_AGENT_VALUE);
        con.header("Content-Type", "application/json;charset=utf-8");
        con.cookies(sessionId).timeout(10000);
        con.data("a", "b");
        //请求参数设置
       // con.requestBody("{\"db\":\"db\",\"sqlId\":\"/log/log@insert\",\"params\":{\"fbranchorgcode\":\"FDJ\",\"foperatercode\":\"cgb311\",\"foperatername\":\"山西华卫药业有限公司\",\"flogtype\":\"8\",\"flogtext\":\"查询:日期从【2021-10-01】至【2021-10-26】药品名称【】批号【】生产厂家【】销往单位【】销往区域【全部】\"}}");
        con.requestBody("{\"db\":\"db\",\"filterModel\":{},\"sortModel\":[],\"limit\":100,\"limitOffset\":0,\"needCount\":true,\"sqlId\":\"/flowquery/flowquery@query\",\"params\":{\"appUserName\":\"cgb311\",\"org\":[\"FDJ\"],\"productName\":\"\",\"batchnumber\":\"\",\"factory\":\"\",\"customerName\":\"\",\"area\":\"-1\",\"startDate\":\"2021-10-01\",\"endDate\":\"2021-10-26\"}}");
        Response login = con.method(Method.POST).ignoreContentType(true).execute();
        System.out.println(login.body());
        return null;
    }
}
